{% extends "base.html" %}

{% block title %}监控面板 - XCQuant{% endblock %}

{% block breadcrumb %}
<nav aria-label="breadcrumb">
    <ol class="breadcrumb">
        <li class="breadcrumb-item"><a href="{{ url_for('index') }}">首页</a></li>
        <li class="breadcrumb-item active">监控面板</li>
    </ol>
</nav>
{% endblock %}

{% block content %}
<!-- 页面标题 -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <h1 class="h3 mb-0 text-gray-800">
        <i class="fas fa-tachometer-alt me-2"></i>监控面板
    </h1>
    <div>
        <button class="btn btn-primary btn-sm" onclick="refreshData()">
            <i class="fas fa-sync-alt me-1"></i>刷新数据
        </button>
        <button class="btn btn-outline-secondary btn-sm" onclick="toggleAutoRefresh()">
            <i class="fas fa-play me-1" id="auto-refresh-icon"></i>
            <span id="auto-refresh-text">开启自动刷新</span>
        </button>
    </div>
</div>

<!-- 系统概览卡片 -->
<div class="row mb-4">
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card border-left-primary shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                            CPU使用率
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800" id="cpu-usage">
                            --
                        </div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-microchip fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card border-left-success shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                            内存使用率
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800" id="memory-usage">
                            --
                        </div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-memory fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card border-left-info shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                            活跃策略
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800" id="active-strategies">
                            --
                        </div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-robot fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card border-left-warning shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                            活跃告警
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800" id="active-alerts">
                            --
                        </div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-exclamation-triangle fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 图表区域 -->
<div class="row mb-4">
    <!-- 系统资源图表 -->
    <div class="col-xl-8 col-lg-7">
        <div class="card shadow mb-4">
            <div class="card-header py-3 d-flex justify-content-between align-items-center">
                <h6 class="m-0 font-weight-bold text-primary">系统资源使用情况</h6>
                <div class="dropdown">
                    <button class="btn btn-sm btn-outline-primary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                        时间范围
                    </button>
                    <ul class="dropdown-menu">
                        <li><a class="dropdown-item" href="#" onclick="changeTimeRange(1)">最近1小时</a></li>
                        <li><a class="dropdown-item" href="#" onclick="changeTimeRange(6)">最近6小时</a></li>
                        <li><a class="dropdown-item" href="#" onclick="changeTimeRange(24)">最近24小时</a></li>
                    </ul>
                </div>
            </div>
            <div class="card-body">
                <div class="chart-area">
                    <canvas id="systemChart" width="100%" height="40"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- 策略收益图表 -->
    <div class="col-xl-4 col-lg-5">
        <div class="card shadow mb-4">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">策略收益分布</h6>
            </div>
            <div class="card-body">
                <div class="chart-pie pt-4 pb-2">
                    <canvas id="profitChart"></canvas>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 策略状态和告警 -->
<div class="row">
    <!-- 策略状态 -->
    <div class="col-lg-6 mb-4">
        <div class="card shadow">
            <div class="card-header py-3 d-flex justify-content-between align-items-center">
                <h6 class="m-0 font-weight-bold text-primary">策略状态</h6>
                <a href="{{ url_for('strategies') }}" class="btn btn-sm btn-outline-primary">
                    查看详情
                </a>
            </div>
            <div class="card-body">
                <div id="strategy-status">
                    <div class="text-center">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 最新告警 -->
    <div class="col-lg-6 mb-4">
        <div class="card shadow">
            <div class="card-header py-3 d-flex justify-content-between align-items-center">
                <h6 class="m-0 font-weight-bold text-primary">最新告警</h6>
                <a href="{{ url_for('alerts') }}" class="btn btn-sm btn-outline-primary">
                    查看全部
                </a>
            </div>
            <div class="card-body">
                <div id="recent-alerts">
                    <div class="text-center">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- WebSocket连接状态 -->
<div class="row">
    <div class="col-12">
        <div class="alert alert-info" id="websocket-status" style="display: none;">
            <i class="fas fa-wifi me-2"></i>
            <span id="websocket-message">正在连接实时数据...</span>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_scripts %}
<script>
let systemChart = null;
let profitChart = null;
let autoRefreshInterval = null;
let websocket = null;
let currentTimeRange = 1; // 默认1小时

$(document).ready(function() {
    // 初始化图表
    initCharts();
    
    // 加载初始数据
    loadDashboardData();
    
    // 连接WebSocket
    connectWebSocket();
});

function initCharts() {
    // 系统资源图表
    const systemCtx = document.getElementById('systemChart').getContext('2d');
    systemChart = new Chart(systemCtx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [{
                label: 'CPU使用率',
                data: [],
                borderColor: 'rgb(54, 162, 235)',
                backgroundColor: 'rgba(54, 162, 235, 0.1)',
                tension: 0.1
            }, {
                label: '内存使用率',
                data: [],
                borderColor: 'rgb(255, 99, 132)',
                backgroundColor: 'rgba(255, 99, 132, 0.1)',
                tension: 0.1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    max: 100,
                    ticks: {
                        callback: function(value) {
                            return value + '%';
                        }
                    }
                }
            },
            plugins: {
                legend: {
                    display: true,
                    position: 'top'
                }
            }
        }
    });

    // 策略收益图表
    const profitCtx = document.getElementById('profitChart').getContext('2d');
    profitChart = new Chart(profitCtx, {
        type: 'doughnut',
        data: {
            labels: [],
            datasets: [{
                data: [],
                backgroundColor: [
                    '#4e73df',
                    '#1cc88a',
                    '#36b9cc',
                    '#f6c23e',
                    '#e74a3b'
                ]
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        }
    });
}

function loadDashboardData() {
    $.get('/api/v1/dashboard/data?refresh=true')
        .done(function(response) {
            if (response.success) {
                updateDashboard(response.data);
            }
        })
        .fail(function() {
            showError('加载监控数据失败');
        });
}

function updateDashboard(data) {
    // 更新概览卡片
    if (data.system && data.system.current) {
        $('#cpu-usage').text(data.system.current.cpu_percent.toFixed(1) + '%');
        $('#memory-usage').text(data.system.current.memory_percent.toFixed(1) + '%');
    }
    
    if (data.strategies && data.strategies.summary) {
        $('#active-strategies').text(data.strategies.summary.active_strategies + ' 个');
    }
    
    if (data.alerts && data.alerts.stats) {
        $('#active-alerts').text(data.alerts.stats.active_count + ' 个');
    }
    
    // 更新系统资源图表
    if (data.system && data.system.chart_data) {
        updateSystemChart(data.system.chart_data);
    }
    
    // 更新策略收益图表
    if (data.strategies && data.strategies.strategies) {
        updateProfitChart(data.strategies.strategies);
    }
    
    // 更新策略状态
    if (data.strategies && data.strategies.strategies) {
        updateStrategyStatus(data.strategies.strategies);
    }
    
    // 更新告警列表
    if (data.alerts && data.alerts.active_alerts) {
        updateRecentAlerts(data.alerts.active_alerts);
    }
}

function updateSystemChart(chartData) {
    if (!chartData.timestamps || chartData.timestamps.length === 0) {
        return;
    }
    
    // 格式化时间标签
    const labels = chartData.timestamps.map(ts => {
        const date = new Date(ts);
        return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
    });
    
    systemChart.data.labels = labels;
    systemChart.data.datasets[0].data = chartData.cpu;
    systemChart.data.datasets[1].data = chartData.memory;
    systemChart.update();
}

function updateProfitChart(strategies) {
    const labels = [];
    const data = [];
    
    strategies.forEach(strategy => {
        if (strategy.total_profit !== 0) {
            labels.push(strategy.name);
            data.push(Math.abs(strategy.total_profit));
        }
    });
    
    if (labels.length === 0) {
        labels.push('暂无数据');
        data.push(1);
    }
    
    profitChart.data.labels = labels;
    profitChart.data.datasets[0].data = data;
    profitChart.update();
}

function updateStrategyStatus(strategies) {
    let html = '';
    
    if (strategies.length === 0) {
        html = '<div class="text-muted">暂无策略</div>';
    } else {
        html = '<div class="table-responsive"><table class="table table-sm">';
        html += '<thead><tr><th>策略名称</th><th>状态</th><th>收益</th><th>胜率</th></tr></thead><tbody>';
        
        strategies.forEach(strategy => {
            const statusClass = getStrategyStatusClass(strategy.status);
            const profitClass = strategy.total_profit >= 0 ? 'text-success' : 'text-danger';
            
            html += `
                <tr>
                    <td>${strategy.name}</td>
                    <td><span class="badge ${statusClass}">${getStatusText(strategy.status)}</span></td>
                    <td class="${profitClass}">${formatCurrency(strategy.total_profit)}</td>
                    <td>${(strategy.win_rate * 100).toFixed(1)}%</td>
                </tr>
            `;
        });
        
        html += '</tbody></table></div>';
    }
    
    $('#strategy-status').html(html);
}

function updateRecentAlerts(alerts) {
    let html = '';
    
    if (alerts.length === 0) {
        html = '<div class="text-muted">暂无告警</div>';
    } else {
        html = '<div class="list-group list-group-flush">';
        
        alerts.slice(0, 5).forEach(alert => {
            const levelClass = getLevelClass(alert.level);
            const levelIcon = getLevelIcon(alert.level);
            const timeAgo = getTimeAgo(alert.created_at);
            
            html += `
                <div class="list-group-item">
                    <div class="d-flex w-100 justify-content-between">
                        <h6 class="mb-1">
                            <i class="${levelIcon} ${levelClass} me-2"></i>
                            ${alert.title}
                        </h6>
                        <small class="text-muted">${timeAgo}</small>
                    </div>
                    <p class="mb-1 small">${alert.message}</p>
                </div>
            `;
        });
        
        html += '</div>';
    }
    
    $('#recent-alerts').html(html);
}

function connectWebSocket() {
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const wsUrl = `${protocol}//${window.location.hostname}:8765`;
    
    try {
        websocket = new WebSocket(wsUrl);
        
        websocket.onopen = function() {
            $('#websocket-status').removeClass('alert-warning alert-danger').addClass('alert-success').show();
            $('#websocket-message').text('实时数据连接已建立');
            
            // 订阅数据频道
            websocket.send(JSON.stringify({
                type: 'subscribe',
                channels: ['dashboard', 'system', 'strategies', 'alerts']
            }));
            
            setTimeout(() => $('#websocket-status').fadeOut(), 3000);
        };
        
        websocket.onmessage = function(event) {
            const message = JSON.parse(event.data);
            
            if (message.type === 'data') {
                // 处理实时数据更新
                if (message.channel === 'dashboard') {
                    updateDashboard(message.data);
                }
            } else if (message.type === 'notification') {
                // 显示通知
                showNotification(message.title, message.message, message.level);
            }
        };
        
        websocket.onclose = function() {
            $('#websocket-status').removeClass('alert-success').addClass('alert-warning').show();
            $('#websocket-message').text('实时数据连接已断开，正在重连...');
            
            // 5秒后重连
            setTimeout(connectWebSocket, 5000);
        };
        
        websocket.onerror = function() {
            $('#websocket-status').removeClass('alert-success').addClass('alert-danger').show();
            $('#websocket-message').text('实时数据连接失败');
        };
        
    } catch (error) {
        console.warn('WebSocket连接失败:', error);
    }
}

function refreshData() {
    loadDashboardData();
}

function toggleAutoRefresh() {
    if (autoRefreshInterval) {
        clearInterval(autoRefreshInterval);
        autoRefreshInterval = null;
        $('#auto-refresh-icon').removeClass('fa-pause').addClass('fa-play');
        $('#auto-refresh-text').text('开启自动刷新');
    } else {
        autoRefreshInterval = setInterval(loadDashboardData, 30000);
        $('#auto-refresh-icon').removeClass('fa-play').addClass('fa-pause');
        $('#auto-refresh-text').text('关闭自动刷新');
    }
}

function changeTimeRange(hours) {
    currentTimeRange = hours;
    loadDashboardData();
}

function getStrategyStatusClass(status) {
    const classMap = {
        'running': 'bg-success',
        'stopped': 'bg-secondary',
        'error': 'bg-danger',
        'paused': 'bg-warning'
    };
    return classMap[status] || 'bg-secondary';
}

function getStatusText(status) {
    const statusMap = {
        'running': '运行中',
        'stopped': '已停止',
        'error': '错误',
        'paused': '已暂停',
        'healthy': '健康',
        'warning': '警告',
        'critical': '严重'
    };
    return statusMap[status] || status;
}

function getLevelClass(level) {
    const classMap = {
        'info': 'text-info',
        'warning': 'text-warning',
        'error': 'text-danger',
        'critical': 'text-danger'
    };
    return classMap[level] || 'text-secondary';
}

function getLevelIcon(level) {
    const iconMap = {
        'info': 'fas fa-info-circle',
        'warning': 'fas fa-exclamation-triangle',
        'error': 'fas fa-times-circle',
        'critical': 'fas fa-exclamation-circle'
    };
    return iconMap[level] || 'fas fa-circle';
}

function formatCurrency(amount) {
    return new Intl.NumberFormat('zh-CN', {
        style: 'currency',
        currency: 'CNY'
    }).format(amount);
}

function getTimeAgo(timestamp) {
    const now = new Date();
    const time = new Date(timestamp);
    const diff = now - time;
    
    const minutes = Math.floor(diff / 60000);
    const hours = Math.floor(diff / 3600000);
    const days = Math.floor(diff / 86400000);
    
    if (days > 0) return days + '天前';
    if (hours > 0) return hours + '小时前';
    if (minutes > 0) return minutes + '分钟前';
    return '刚刚';
}

function showError(message) {
    // 显示错误提示
    const alert = `
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-circle me-2"></i>
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    $('main').prepend(alert);
}

function showNotification(title, message, level) {
    // 显示通知
    const levelClass = getLevelClass(level);
    const notification = `
        <div class="alert alert-${level === 'error' ? 'danger' : level} alert-dismissible fade show" role="alert">
            <strong>${title}</strong> ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    $('main').prepend(notification);
    
    // 5秒后自动消失
    setTimeout(() => {
        $('.alert').first().fadeOut();
    }, 5000);
}
</script>
{% endblock %}